/*
 * @Author: JohnYang
 * @Date: 2020-09-22 20:57:03
 * @LastEditors: JohnYang
 * @LastEditTime: 2020-09-30 22:25:10
 */
import { login, logout } from "@/api/login";
import { getToken, setToken, removeToken } from "@/utils/auth";

const user = {
  state: {
    token: getToken(),
    name: "",
    role: ""
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token;
    },
    SET_ACCOUNT: (state, name) => {
      state.name = name;
      localStorage.setItem("SET_ACCOUNT", name);
    },
    SET_ROLE: (state, role) => {
      state.role = role;
      localStorage.setItem("SET_ROLE", role);
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar;
    },
    GET_STORAGE: state => {
      state.account = localStorage.getItem("SET_ACCOUNT");
      state.role = localStorage.getItem("SET_ROLE");
    }
  },

  actions: {
    ReadMsg({ commit }) {
      commit("GET_STORAGE");
    },
    // 登录
    Login({ commit }, userInfo) {
      const username = userInfo.username.trim();
      const password = userInfo.password;
      return new Promise((resolve, reject) => {
        login(username, password)
          .then(res => {
            const data = res.data;
            setToken(data.token);
            commit("SET_TOKEN", data.token);
            commit("SET_ROLE", data.admin);
            commit("SET_ACCOUNT", username);
            resolve();
          })
          .catch(error => {
            reject(error);
          });
      });
    },

    // 退出系统
    LogOut({ commit, state }) {
      return new Promise((resolve, reject) => {
        logout(state.token)
          .then(() => {
            commit("SET_TOKEN", "");
            commit("SET_ACCOUNT", "");
            commit("SET_ROLE", "");
            removeToken();
            resolve();
          })
          .catch(error => {
            reject(error);
          });
      });
    },

    // 前端 登出
    FedLogOut({ commit }) {
      return new Promise(resolve => {
        commit("SET_TOKEN", "");
        commit("SET_ACCOUNT", "");
        commit("SET_ROLE", "");
        removeToken();
        resolve();
      });
    }
  }
};

export default user;
